﻿ using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

namespace DigitalAmele.WebApp.s3capcha
{


    /// <summary>
    /// Summary description for s3capcha
    /// </summary>
    public class s3capcha
    {
        public static string s3name = "s3capcha";
        public static string[] IconNames;
        public static string[] IconTitles;
        public static int Width;
        public static int Height;
        public static string Message;
        public static string Folder;
        public static string Extention;
        private static string RowTemplate = "<div style=\"float:left\"><span>{0} <input type=\"radio\" name=\"s3capcha\" value=\"{1}\" /></span><div style=\"background:url({2}) bottom left no-repeat; width:{3}px; height:{4}px;cursor:pointer;display:none;\" class=\"img\"></div></div>";

        private static bool LoadConfig()
        {
            string FilePath = "~/s3capcha/config.xml";
            FilePath = HttpContext.Current.Server.MapPath(FilePath);
            if (System.IO.File.Exists(FilePath))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(FilePath);
                string BaseNode = "/s3capcha/icons/";

                XmlNode node = doc.SelectSingleNode(BaseNode + "name");
                IconNames = node.InnerText.Split(new char[] { ',' });

                node = doc.SelectSingleNode(BaseNode + "title");
                IconTitles = node.InnerText.Split(new char[] { ',' });

                node = doc.SelectSingleNode(BaseNode + "width");
                Width = Convert.ToInt32(node.InnerText);

                node = doc.SelectSingleNode(BaseNode + "height");
                Height = Convert.ToInt32(node.InnerText);

                node = doc.SelectSingleNode(BaseNode + "ext");
                Extention = node.InnerText;

                node = doc.SelectSingleNode(BaseNode + "folder");
                Folder = node.InnerText;

                node = doc.SelectSingleNode("s3capcha/message");
                Message = node.InnerText;

                doc = null;
                return true;
            }
            return false;
        }

        public static List<int> shuffle(List<int> input)
        {
            List<int> output = new List<int>();
            Random rnd = new Random();

            int FIndex;
            while (input.Count > 0)
            {
                FIndex = rnd.Next(0, input.Count);
                output.Add(input[FIndex]);
                input.RemoveAt(FIndex);
            }

            input.Clear();
            input = null;
            rnd = null;

            return output;
        }

        public static bool Verify(object SessionValue, string FormValue)
        {
            bool IsValid = false;
            if (SessionValue != null)
            {
                if (!string.IsNullOrEmpty(FormValue))
                {
                    if (FormValue == Convert.ToString(SessionValue))
                    {
                        IsValid = true;
                    }
                }
            }
            return IsValid;
        }

        public static string GetHtmlCodes(string PathTo, out int SessionValue)
        {
            bool HasValue = false;
            if (string.IsNullOrEmpty(Message))
                HasValue = LoadConfig();
            else
                HasValue = true;

            if (HasValue)
            {
                Random Rnd = new Random();
                int RandomIndex = Rnd.Next(0, IconNames.Length);

                List<int> values = new List<int>();
                for (int i = 0; i < IconNames.Length; i++)
                    values.Add(i);
                values = shuffle(values);

                string WriteThis = "<div class=\"s3capcha\"><p>" + string.Format(Message, "<strong>" + IconTitles[values[RandomIndex]] + "</strong>") + "</p>";
                int[] RandomValues = new int[IconNames.Length];
                for (int i = 0; i < IconNames.Length; i++)
                {
                    RandomValues[i] = Rnd.Next();
                    WriteThis += string.Format(RowTemplate,
                         IconTitles[values[i]],
                         RandomValues[i],
                         PathTo + "/icons/" + Folder + "/" + IconNames[values[i]] + "." + Extention,
                         Width,
                         Height);
                }
                WriteThis += "<div style=\"clear:left\"></div></div>";
                SessionValue = RandomValues[RandomIndex];
                return WriteThis;
            }
            else
            {
                SessionValue = -1;
                return "Invalid data, config file not found";
            }
        }
    }
}
